package com.guofen.controller.shlj;

import com.guofen.pojo.ShljAbnormalGarbage;
import com.guofen.pojo.ShljDeodorizationtowerWaterChange1;
import com.guofen.pojo.ShljYijingStationSelling;
import com.guofen.service.shlj.YijingStationSellingService;
import com.guofen.service.shlj.impl.YijingStationSellingServiceImpl;
import com.guofen.util.result.Result;
import com.guofen.util.result.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("/shlj/yijingStationSelling")
@Controller
@Api(tags = "YijingStationSellingController", description = "易净场站回收物资外卖记录表")
public class YijingStationSellingController {

    @Autowired
    private YijingStationSellingService service;

    //保存
    @ApiOperation("添加记录")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Result add(@ApiParam(name="name",value="物品名称",required=true) @RequestParam String name,
                      @ApiParam(name="amountstr",value="数量",required=true) @RequestParam String amountstr,
                      @ApiParam(name="remarks",value="备注",required=true) @RequestParam String remarks){
        Double amount = Double.parseDouble(amountstr);
        if (service.add(name,amount,remarks))
            return ResultGenerator.genSuccessResult();
        else
            return ResultGenerator.genFailResult("保存失败");
    }

    @ApiOperation("获取 当日 最新 一条记录")
    @RequestMapping(value = "/getlast",method = RequestMethod.GET)
    @ResponseBody
    public Result get(){
        return  ResultGenerator.genSuccessResult(service.getlast());
    }

    @ApiOperation("获取 当日 所有记录")
    @RequestMapping(value = "/getrecord_day",method = RequestMethod.GET)
    @ResponseBody
    public Result getrecord_day(){
        return  ResultGenerator.genSuccessResult(service.getrecord_day());
    }

    @ApiOperation("获取 当日 所有垃圾重量(顺序为塑料，塑料袋，饭盒，纸，铁铝盒，玻璃瓶，饮料瓶)")
    @RequestMapping(value = "/getamount_day",method = RequestMethod.GET)
    @ResponseBody
    public Result getamount_day(){
        return  ResultGenerator.genSuccessResult(service.getamount_day());
    }

    @ApiOperation("删除记录")
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id) {
        return ResultGenerator.genSuccessResult(service.delete(id));
    }

    @ApiOperation("修改记录")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public Result update(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id,
                         @ApiParam(name="name",value="物品名称",required=true) @RequestParam String name,
                         @ApiParam(name="amount",value="数量",required=true) @RequestParam Double amount,
                         @ApiParam(name="remarks",value="备注",required=true) @RequestParam String remarks) {
        ShljYijingStationSelling record = new ShljYijingStationSelling();
        record.setId(id);
        record.setName(name);
        record.setAmount(amount);
        record.setRemarks(remarks);
        return ResultGenerator.genSuccessResult(service.update(record));
    }

    @ApiOperation("查找记录")
    @RequestMapping(value = "/select",method = RequestMethod.POST)
    @ResponseBody
    public Result select(@ApiParam(name="pageSize",value="页容量",required=true) @RequestParam Integer pageSize,
                         @ApiParam(name="currentPage",value="当前页",required=true) @RequestParam Integer currentPage,
                         @ApiParam(name="startTime",value="开始时间") Long startTime,
                         @ApiParam(name="endTime",value="截止时间") Long endTime) {
        if (startTime == null || endTime == null)
            return ResultGenerator.genSuccessResult(service.get(pageSize, currentPage));
        else
            return ResultGenerator.genSuccessResult(service.getByTime(pageSize, currentPage, startTime, endTime));
    }

    @ApiOperation("EXCEL批量添加记录")
    @PostMapping("/addFromExcel")
    @ResponseBody
    public Result doRegisterFromExcel(@RequestParam("file") MultipartFile file){
        String EXCEL_XLS = "xls";
        String EXCEL_XLSX = "xlsx";

        if (file.isEmpty())
            return ResultGenerator.genFailResult("文件为空");

        List<Boolean> registerResult = new ArrayList<>();
        try {
            //根据路径获取这个操作excel的实例
            Sheet sheet = null;
            Row row = null;
            if (file.getOriginalFilename().endsWith(EXCEL_XLS)) {
                //用于xls文件的读取
                HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
                sheet = wb.getSheetAt(0);
            } else if (file.getOriginalFilename().endsWith(EXCEL_XLSX)) {
                //用于xlsx文件的读取
                XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
                //根据页面index 获取sheet页
                sheet = wb.getSheetAt(0);
            }
            //实体类集合
            List<ShljYijingStationSelling> shljYijingStationSellings = new ArrayList<>();

            //XSSFRow row = null;
            //循环sheet页中数据从第三行开始，第一行是导入说明，第二行是标题
//            System.out.println(sheet.getPhysicalNumberOfRows());
            int counter = 0;
            String date= "";
            String remarks = "";
            for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);
                //如果表格第二列和第三列为空
                if((row.getCell(0)==null&&row.getCell(1)==null&&row.getCell(2)==null&&row.getCell(3)==null&&
                        row.getCell(4)==null&&row.getCell(5)==null&&row.getCell(6)==null&&row.getCell(7)==null)){
                    continue;
                }
                ShljYijingStationSelling shljYijingStationSelling = new ShljYijingStationSelling();
                //表中第1列，日期
                if(row.getCell(0)!=null){
                    if (counter % 7 == 0) {
                        Cell cell = row.getCell(0);
                        Date d = cell.getDateCellValue();
                        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
                        date = formater.format(d);
                    }
                    shljYijingStationSelling.setDate(date);
                }
                if(row.getCell(1)!=null){
                    Cell cell = row.getCell(1);
                    cell.setCellType(CellType.STRING);
                    shljYijingStationSelling.setName(cell.getStringCellValue());
                }
                if(row.getCell(2)!=null){
                    Cell cell = row.getCell(2);
                    double amount = Double.parseDouble(cell.getStringCellValue());
                    shljYijingStationSelling.setAmount(amount);
                }
                if(row.getCell(3)!=null){
                    Cell cell = row.getCell(3);
                    cell.setCellType(CellType.STRING);
                    shljYijingStationSelling.setUnit(cell.getStringCellValue());
                }
                if(row.getCell(4)!=null){
                    Cell cell = row.getCell(4);
                    double price = Double.parseDouble(cell.getStringCellValue());
                    shljYijingStationSelling.setPrice(price);
                }
                if(row.getCell(5)!=null){
                    Cell cell = row.getCell(5);
                    double totalPrice = Double.parseDouble(cell.getStringCellValue());
                    shljYijingStationSelling.setTotalPrice(totalPrice);
                }
                if(row.getCell(6)!=null){
//                    Cell cell = row.getCell(6);
//                    cell.setCellType(CellType.STRING);
//                    shljAbnormalGarbage.setGarbageUnit(cell.getStringCellValue());
                }
                if(row.getCell(7)!=null){
                    if (counter % 7 == 0) {
                        Cell cell = row.getCell(7);
                        cell.setCellType(CellType.STRING);
                        remarks = cell.getStringCellValue();
                    }
                    shljYijingStationSelling.setRemarks(remarks);
                }
//                System.out.println(shljAbnormalGarbage.getWagonNumber());
                shljYijingStationSellings.add(shljYijingStationSelling);
                counter++;
            }
            for (ShljYijingStationSelling u : shljYijingStationSellings) {
                Boolean test = false;
                test = registerResult.add(test = service.addFormExcel(
                        u.getDate(),u.getName(), u.getAmount(), u.getUnit(),
                        u.getPrice(), u.getTotalPrice(), u.getRemarks()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.genSuccessResult(registerResult);
    }
}
